package com.yanqu.controller;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.yanqu.data.entity.HistoryGoodsGetData;
import com.yanqu.data.entity.setting.CustomGoodsBaseValueData;
import com.yanqu.data.entity.setting.CustomThresholdRatioData;
import com.yanqu.data.entity.setting.GoodsIgnoreData;
import com.yanqu.manager.UserGetGoodsMonitorMgr;
import com.yanqu.manager.UserGoodsMonitorSettingMgr;
import com.yanqu.road.entity.admin.AdminResult;
import com.yanqu.road.entity.admin.AdminResult2;
import com.yanqu.road.utils.date.DateHelper;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * wmm 道具阈值管理
 * 71 道具阈值监控
 */
@RestController
@RequestMapping("/")
public class GoodsMonitorManagerController {

    public static Object locker = new Object();

    /**
     *  71.1 查询道具阈值 （没有倍率）
     *  查询设定的阈值或者内存中的基准值 取大值
     */
    @ResponseBody
    @RequestMapping(value = "propThreshold/query", method = RequestMethod.POST, produces = {"application/json;charset=UTF-8"})
    public String propThresholdQuery(HttpServletRequest request, @RequestBody JSONObject json){
        int channelId = json.getIntValue("channelId");
        int vip = json.getIntValue("userGroup");
        int goodsId = json.getIntValue("goodsId");

        int todayZeroTime = (int)(DateHelper.getZeroTimeStamp(System.currentTimeMillis()) / 1000);

        //历史数据统计的不分渠道
        HistoryGoodsGetData baseValue = UserGetGoodsMonitorMgr.getBaseValueV2(todayZeroTime, vip, goodsId);

        //后台设置的阈值
        CustomGoodsBaseValueData customGoodsBaseValueData = UserGoodsMonitorSettingMgr.getCustomGoodsBaseValueData(channelId, vip, goodsId);
        if(customGoodsBaseValueData == null) {
            //特定渠道没有，就查询通用渠道
            customGoodsBaseValueData = UserGoodsMonitorSettingMgr.getCustomGoodsBaseValueData(0, vip, goodsId);
        }

        AdminResult2 result = AdminResult2.defaultInstance();

        Map<String, Object> map = new HashMap<>();
        map.put("goodId", goodsId);
        map.put("channelId", channelId);
        map.put("userGroup", vip);
        map.put("numThreshold", 0);
        map.put("countThreshold", 0);

        //如果有历史数据的基准值（目前不区分渠道），则使用
        if(baseValue != null){
            map.put("channelId", 0);
            map.put("numThreshold", baseValue.getMaxNum());
            map.put("countThreshold", baseValue.getMaxTimes());
        }

        //如果有特定的设置，则覆盖历史基准值
        if(customGoodsBaseValueData != null){
            map.put("channelId", customGoodsBaseValueData.getChannelId());
            map.put("userGroup", customGoodsBaseValueData.getVip());
            map.put("goodId", customGoodsBaseValueData.getGoodsId());
            map.put("numThreshold", customGoodsBaseValueData.getMaxNum());
            map.put("countThreshold", customGoodsBaseValueData.getMaxTimes());
        }
        result.getData().add(map);
        return result.toJsonString();
    }
    /**
     *  71.2 编辑阈值
     *  新增或者修改设定的阈值（未叠加倍率）
     */
    @ResponseBody
    @RequestMapping(value = "propThreshold/edit", method = RequestMethod.POST, produces = {"application/json;charset=UTF-8"})
    public String propThresholdEdit(HttpServletRequest request, @RequestBody JSONObject json){
        //正常传0即可，不区分渠道
        int channelId = json.getIntValue("channelId");
        int vip = json.getIntValue("userGroup");
        int goodsId = json.getIntValue("goodsId");
        int numThreshold = json.getIntValue("numThreshold");
        int countThreshold = json.getIntValue("countThreshold");

        synchronized (locker) {
            CustomGoodsBaseValueData customGoodsBaseValueData = UserGoodsMonitorSettingMgr.getCustomGoodsBaseValueData(channelId, vip, goodsId);
            if(customGoodsBaseValueData == null){
                customGoodsBaseValueData = new CustomGoodsBaseValueData();
                customGoodsBaseValueData.setChannelId(channelId);
                customGoodsBaseValueData.setVip(vip);
                customGoodsBaseValueData.setGoodsId(goodsId);
                customGoodsBaseValueData.setMaxNum(numThreshold);
                customGoodsBaseValueData.setMaxTimes(countThreshold);
                customGoodsBaseValueData.setInsertOption();
                UserGoodsMonitorSettingMgr.addCustomGoodsBaseValueData(customGoodsBaseValueData);
            }else {
                customGoodsBaseValueData.setMaxNum(numThreshold);
                customGoodsBaseValueData.setMaxTimes(countThreshold);
            }
        }
        return AdminResult.defaultInstance().toJsonString();
    }

    /**
     * 71.3 刷新配置
     * 如果是设置的渠道0的基准值，则需要刷新重算
     */
    @ResponseBody
    @RequestMapping(value = "propThreshold/refresh", method = RequestMethod.POST, produces = {"application/json;charset=UTF-8"})
    public String propThresholdRefresh(HttpServletRequest request, @RequestBody JSONObject json){

        int channelId = json.getIntValue("channelId");

        int todayZeroTime = (int)(DateHelper.getZeroTimeStamp(System.currentTimeMillis()) / 1000);

        //重新计算内存的基准值
        UserGetGoodsMonitorMgr.reCalDayBaseValue(todayZeroTime);

        UserGoodsMonitorSettingMgr.setLastUpdateTime(System.currentTimeMillis());


        return AdminResult.defaultInstance().toJsonString();
    }

    /**
     * 71.4 新增/编辑/删除 用户群阈值
     */
    @ResponseBody
    @RequestMapping(value = "propThreshold/editGroup", method = RequestMethod.POST, produces = {"application/json;charset=UTF-8"})
    public String propThresholdeditGroup(HttpServletRequest request, @RequestBody JSONObject json){

        int channelId = json.getIntValue("channelId");
        int vip = json.getIntValue("userGroup");
        int thresholdType = json.getIntValue("thresholdType");
        JSONArray thresholdRange = json.getJSONArray("thresholdRange");
        int thresholdRatio = json.getIntValue("thresholdRatio");

        //0次数阈值 1数量阈值
        if(thresholdType != 0 && thresholdType != 1){
            return AdminResult.failMsg("类型错误").toJsonString();
        }

        int type = json.getIntValue("type");

        long id = json.getLongValue("id");

        List<Integer> rangeList = new ArrayList<>();

        for (int i = 0; i < thresholdRange.size(); i++) {
            rangeList.add(thresholdRange.getInteger(i));
        }

        synchronized (locker) {
            List<CustomThresholdRatioData> dataList = UserGoodsMonitorSettingMgr.getCustomThresholdRatioData(channelId, vip, thresholdType);
            CustomThresholdRatioData data = null;
            if(dataList != null){
                for (CustomThresholdRatioData ratioData : dataList) {
                    if(ratioData.getDbId() == id){
                        data = ratioData;
                    }
                }
            }
            if(data == null){
                data = new CustomThresholdRatioData();
                data.setChannelId(channelId);
                data.setVip(vip);
                data.setThresholdType(thresholdType);
                data.setThresholdRatio(thresholdRatio);
                data.setThresholdRange(rangeList);
                data.setInsertOption();
                UserGoodsMonitorSettingMgr.addCustomThresholdRatioData(data);
            }else {
                data.setThresholdRatio(thresholdRatio);
                data.setThresholdRange(rangeList);
                if(type == 2){
                    data.setDel(1);
                }
            }
        }
        return AdminResult.defaultInstance().toJsonString();
    }

    /**
     *  71.6 新增/编辑/删除 道具白名单
     */
    @ResponseBody
    @RequestMapping(value = "propThreshold/editWhite", method = RequestMethod.POST, produces = {"application/json;charset=UTF-8"})
    public String propThresholdEditWhite(HttpServletRequest request, @RequestBody JSONObject json){

        int channelId = json.getIntValue("channelId");
        int type = json.getIntValue("type");
        int goodsId = json.getIntValue("goodsId");

        synchronized (locker) {
            GoodsIgnoreData data = UserGoodsMonitorSettingMgr.getGoodsIgnoreData(channelId, goodsId);
            if (type == 0){
                if(data != null){
                    return AdminResult.failMsg("已存在").toJsonString();
                }
                data = new GoodsIgnoreData();
                data.setChannelId(channelId);
                data.setGoodsId(goodsId);
                data.setInsertOption();
                UserGoodsMonitorSettingMgr.addGoodsIgnoreData(data);
            }else if(type == 1){
                if(data == null){
                    return AdminResult.failMsg("不存在").toJsonString();
                }

            }else {
                if(data == null){
                    return AdminResult.failMsg("不存在").toJsonString();
                }
                data.setDeleted(1);
            }
        }

        return AdminResult.defaultInstance().toJsonString();
    }

    /**
     *  71.8 获取最后刷新配置时间
     */
    @ResponseBody
    @RequestMapping(value = "propThreshold/getRefreshTime", method = RequestMethod.POST, produces = {"application/json;charset=UTF-8"})
    public String propThresholdGetRefreshTime(HttpServletRequest request, @RequestBody JSONObject json){

        AdminResult result = new AdminResult();

        long lastUpdateTime = UserGoodsMonitorSettingMgr.getLastUpdateTime();
        if(lastUpdateTime != 0){
            result.getData().put("refreshTime", DateHelper.getCurrentDateTimeString(lastUpdateTime));
        }


        return result.toJsonString();
    }

    /**
     *  71.5查询用户群阈值
     */
    @ResponseBody
    @RequestMapping(value = "propThreshold/queryGroup", method = RequestMethod.POST, produces = {"application/json;charset=UTF-8"})
    public String propThresholdQueryGroup(HttpServletRequest request, @RequestBody JSONObject json){

        int channelId = json.getIntValue("channelId");
        int vip = json.getIntValue("userGroup");
        int thresholdType = json.getIntValue("thresholdType");

        List<CustomThresholdRatioData> customThresholdRatioData = UserGoodsMonitorSettingMgr.getCustomThresholdRatioData(channelId, vip, thresholdType);

        AdminResult2 adminResult = AdminResult2.defaultInstance();

        if(customThresholdRatioData != null && !customThresholdRatioData.isEmpty()){
            for (CustomThresholdRatioData data : customThresholdRatioData) {
                Map<String, Object> map = new HashMap<>();
                map.put("id", data.getDbId());
                map.put("channelId", data.getChannelId());
                map.put("userGroup", data.getVip());
                map.put("thresholdType", data.getThresholdType());
                map.put("thresholdRange", data.getThresholdRange());
                map.put("thresholdRatio", data.getThresholdRatio());
                adminResult.getData().add(map);
            }
        }
        return adminResult.toJsonString();
    }

}
